<?php

class IndexController extends Zend_Controller_Action {

    public function init() {

        /* Initialize action controller here */
    }

    public function indexAction() {
        $this->view->resultAvail = true;
        #defaults        
        $this->view->isSearched = false;
        #brands
        $brandDb = new Admin_Model_Brand();
        $brandsByMenu = $brandDb->getAllBrands();
        $this->view->allBrands = $brandsByMenu;
        $this->view->brandsWithStateId = json_encode($brandDb->getBrandsWithStateId());
        #states
        $stateDb = new Admin_Model_State();
        $allStates = $stateDb->getAllStateArray();
        $this->view->allStates = json_encode($allStates);
        #city
        $cityDb = new Admin_Model_City();
        $allCityArray = $cityDb->getAllCityArray(false);
        $this->view->allCity = json_encode($allCityArray);

        #now search
        if (isset($_POST['submit'])) {
            $values = $_POST;
            $this->view->isSearched = true;
            $this->view->searchFormValues = $values;
            $searchBrand = $values['brand'];
            $searchOption = $values['searchOption1'];
            switch ($searchOption) {
                case "state":
                    $searchState = $values['state'];
                    $searchCity = $values['city'];
                    break;
                case "zip":
                    $searchZipCode = $values['zip'];
                    break;
            }
            $brandImage = "";
            $searchedArrayResult = array();
            $storeDb = new Admin_Model_Store();
            $fetchAll = $storeDb->fetchAll("true", true);
            foreach ($fetchAll as $storeValue) { #store details                        
                $brandMatched = false;
                $stateMatched = false;
                $cityMatched = false;
                $zipMatched = false;
                foreach ($storeValue['brands'] as $brandValues) {#checking for brand
                    if ($brandValues['brand_id'] == $searchBrand) {
                        $brandImage = $brandValues['brand_image'];
                        $brandMatched = true;
                    }
                }
                if ($brandMatched) {
                    #state and city matching
                    if ($searchOption == "state") {
                        $zipMatched = true;
                        $stateMatched = ($storeValue['location']['state']['id'] == $searchState) ? true : false;
                        $cityMatched = ($storeValue['location']['city']['id'] == $searchCity) ? true : false;
                    } else {
                        #search for zipcode
                        $stateMatched = true;
                        $cityMatched = true;
                        $zipMatched = ($storeValue['location']['zipcode']['code'] == $searchZipCode) ? true : false;
                    }
                }
                #add store to out put array                
                if ($brandMatched && $stateMatched && $cityMatched && $zipMatched) {
                    array_push($searchedArrayResult, $storeValue);
                }
            }

            $this->view->brandImage = $brandImage;
            $this->view->searchedArrayResult = $searchedArrayResult;
            if (sizeof($searchedArrayResult) == 0) {
                $this->view->resultAvail = false;
            }
        }
    }

    public function menuAction() {
        $this->view->resultAvail = true;
        #id
        $menuId = $this->getinputidAction();
        $menuDb = new Admin_Model_Menu();
        $parentOfMenuId = $menuDb->getParentOfMenuId($menuId);
        $parentMenuKey = str_replace(" ", "-", $parentOfMenuId['name']);
        $this->view->parentMenuKey = $parentMenuKey;
        #defaults        
        $this->view->isSearched = false;
        #brands
        $brandDb = new Admin_Model_Brand();
        $brandsByMenu = $brandDb->getBrandsByMenu($menuId);
        $this->view->allBrands = $brandsByMenu;
        $this->view->brandsWithStateId = json_encode($brandDb->getBrandsWithStateId());
        #states
        $stateDb = new Admin_Model_State();
        $allStates = $stateDb->getAllStateArray();
        $this->view->allStates = json_encode($allStates);
        #city
        $cityDb = new Admin_Model_City();
        $allCityArray = $cityDb->getAllCityArray(false);
        $this->view->allCity = json_encode($allCityArray);

        #now search
        if (isset($_POST['submit'])) {
            $values = $_POST;
            $this->view->isSearched = true;
            $this->view->searchFormValues = $values;
            $searchBrand = $values['brand'];
            $searchOption = $values['searchOption1'];
            switch ($searchOption) {
                case "state":
                    $searchState = $values['state'];
                    $searchCity = $values['city'];
                    break;
                case "zip":
                    $searchZipCode = $values['zip'];
                    break;
            }
            $brandImage = "";
            $searchedArrayResult = array();
            $storeDb = new Admin_Model_Store();
            $fetchAll = $storeDb->fetchAll("true", true);
            foreach ($fetchAll as $storeValue) { #store details                        
                $brandMatched = false;
                $stateMatched = false;
                $cityMatched = false;
                $zipMatched = false;
                foreach ($storeValue['brands'] as $brandValues) {#checking for brand
                    if ($brandValues['brand_id'] == $searchBrand) {
                        $brandImage = $brandValues['brand_image'];
                        $brandMatched = true;
                    }
                }
                if ($brandMatched) {
                    #state and city matching
                    if ($searchOption == "state") {
                        $zipMatched = true;
                        $stateMatched = ($storeValue['location']['state']['id'] == $searchState) ? true : false;
                        $cityMatched = ($storeValue['location']['city']['id'] == $searchCity) ? true : false;
                    } else {
                        #search for zipcode
                        $stateMatched = true;
                        $cityMatched = true;
                        $zipMatched = ($storeValue['location']['zipcode']['code'] == $searchZipCode) ? true : false;
                    }
                }
                #add store to out put array                
                if ($brandMatched && $stateMatched && $cityMatched && $zipMatched) {
                    array_push($searchedArrayResult, $storeValue);
                }
            }

            $this->view->brandImage = $brandImage;
            $this->view->searchedArrayResult = $searchedArrayResult;
            if (sizeof($searchedArrayResult) == 0) {
                $this->view->resultAvail = false;
            }
        }
    }

    /**
     * Get ID.     
     */
    public function getinputidAction() {
        $filters = array(
            'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
        );
        $validators = array(
            'id' => array('Int')
        );
        $input = new Zend_Filter_Input($filters, $validators);
        $input->setData($this->getRequest()->getParams());
        $id = $input->id; // id
        return $id;
    }

    public function faqAction() {
        $db = new Admin_Model_Faq();
        $fetchAll = $db->fetchAll(true);
        $this->view->allQues = $fetchAll;
    }

    public function tcAction() {
        $db = new Admin_Model_Tc();
        $tc = $db->getTc();
        $this->view->tc = $tc;
    }

    public function sendmsgAction() {
        $storeID = $this->getinputidAction();
        $this->_helper->layout()->disableLayout();
        $isUserNew = false;
        $form = new Application_Form_Sendmsg();
        $form->storeId->setValue($storeID);
        $this->view->form = $form;
        $this->view->showForm = true;
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();

                $emailData = array(
                    'email' => $values['email'],
                    'events' => array(
                        'dropped' => '',
                        'delivered' => '',
                        'bounce' => '',
                        'open' => '',
                        'click' => '',
                        'spamreport' => '',
                        'unsubscribe' => ''
                    )
                );
                $smsData = array(
                    'mobile' => null,
                    'sent' => false,
                    'isVerified' => true,
                    'isDnd' => false,
                );
                $data = array(
                    'name' => $values['name'],
                    'email' => json_encode($emailData),
                    'sms' => json_encode($smsData),
                    'date' => strtotime(date('c'))
                );

                $db = new Admin_Model_Sentnotifications();
                $insertId = $db->addNew($data); //important
                $storeDb = new Admin_Model_Store();
                $storeById = $storeDb->getStoreById($values['storeId'], true);
                if ($values['email'] != null) {
                    $body = "<b>Store Name:</b> " . $storeById['store_name'] . "<br><b>Address:</b> " . $storeById['address1'] . " " . $storeById['address2'] . "<br>" . $storeById['location']['city']['name'] . ", " . $storeById['location']['state']['name'] . ", PIN " . $storeById['location']['zipcode']['code'] . "<br><b>Contact No:</b> " . $storeById['contact1'];
                    if (!empty($storeById['contact2']) || $storeById['contact2'] != null) {
                        $body .= "," . $storeById['contact2'];
                    }
                    $body .= "<br><b>Email: </b>" . $storeById['email'];
                    $sendData = array();
                    $sendData['toEmail'] = $values['email'];
                    $sendData['toName'] = $values['name'];
                    $sendData['subject'] = "Contact Details of Store";
                    $sendData['body'] = $body;
                    $sendData['uniqueArgs'] = array('insertId' => $insertId, 'from' => 'localhost');
                    $this->sendWebMail($sendData);
                }
                if ($values['mobile'] != null) {
                    $optionsDb = new Admin_Model_Options();
                    $fullOnSmsDetails = $optionsDb->getFullOnSmsDetails();

                    $message = $storeById['store_name'] . ', ' . $storeById['address1'] . " " . $storeById['address2'] . ", " . $storeById['location']['city']['name'] . ", " . $storeById['location']['state']['name'] . ", PIN " . $storeById['location']['zipcode']['code'] . ', ' . $storeById['email'] . ' Call: ' . $storeById['contact1'];
                    if (!empty($storeById['contact2']) || $storeById['contact2'] != null) {
                        $message .= ',' . $storeById['contact2'];
                    }
                    #check for validation 
                    $mobileValidationDb = new Admin_Model_Mobilevalidation();
                    $byMobile = $mobileValidationDb->getByMobile($values['mobile']);
                    $mobileNumber = $values['mobile'];
                    if (sizeof($byMobile) == 0) { #if entry not founded then create new.
                        $digits = 4;
                        $code = rand(pow(10, $digits - 1), pow(10, $digits) - 1);
                        $mobileValidationDb->addNew(array(
                            'mobile_number' => $mobileNumber,
                            'verification_code' => $code,
                            'verified' => false,
                            'message_queue' => $message,
                            'notification_id' => $insertId
                        ));
                        $isUserNew = true;
                        $smsData = array(
                            'mobile' => $mobileNumber,
                            'sent' => false,
                            'isDnd' => false,
                            'isVerified' => false,
                        );
                        $db->update(array(
                            'sms' => json_encode($smsData),
                                ), $insertId);
                        $message = "Hello " . $values['name'] . ', your validation code is ' . $code . ".";
//                        print_r($message);
                        $this->sendRouteSms($message, $mobileNumber);
                        // $this->sendSMSFunction($fullOnSmsDetails, $mobileNumber, $message);
                    } else { #check if user has validated his mobile number.
                        if ($byMobile['isVerified']) { #mobile is verified
//                            $messageLength = strlen($message); #check message length                      
//                            if ($messageLength > 140) {
//                                $sendMessage = array(
//                                    substr($message, 0, 139),
//                                    substr($message, 139, $messageLength - 140),
//                                );
//                            } else {
//                                $sendMessage = array($message);
//                            }
//                            foreach ($sendMessage as $message) {
//                                echo 'm1: ' . $message . '<br>';
//                                $smsSender = new System_Smssender();
//                                $smsSender->Sender("sms6.routesms.com", "8080", "sagupta", "sag15pta", "savan-localhost", $message, "919428233422", 0, 0);                                
//                            }
                            $isSent = $this->sendRouteSms($message, $mobileNumber);
                            $smsData = array(
                                'mobile' => $mobileNumber,
                                'sent' => $isSent,
                                'isVerified' => true,
                                'isDnd' => false,
                            );
                            $db->update(array(
                                'sms' => json_encode($smsData),
                                    ), $insertId);
                        } else { #mobile is not verified
                            $mobileValidationDb->updateByMobile(array(
                                'message_queue' => $message,
                                'notification_id' => $insertId
                                    ), $mobileNumber);
                            $isUserNew = true;
                            $message = "Hello " . $values['name'] . ', You have not verified your number. your validation code is ' . $byMobile['code'] . ".";
                            $this->sendRouteSms($message, $mobileNumber);
                            //$this->sendSMSFunction($fullOnSmsDetails, $mobileNumber, $message);
                        }
                    }
                }
                $this->view->showForm = false;
                $this->view->isUserNew = $isUserNew;
                if ($isUserNew) {
                    $this->_redirect("/verify/$mobileNumber");
                }
            }
        }
    }

    public function sendRouteSms($message, $mobileNumber) {
        $smsSender = new System_Smssender();
//                        $smsSender->Sender($host, $port, $username, $password, $sender, $message, $mobile, $msgtype, $dlr);
        $smsSender->Sender("sms6.routesms.com", "8080", "sagupta", "sag15pta", "UPDATE", $message, "$mobileNumber", 0, 1);
        $response = $smsSender->Submit();
        $value = explode("|", $response);
        if ($value[0] == 1701) {
            return true;
        } else {
            return false;
        }
    }

    public function sendSMSFunction($fullOnSmsDetails, $mobile, $message) {
        $url = "http://" . $_SERVER['SERVER_NAME'] . "/Sms/sendsms.php";
        $finalUrl = $url . '?uid=' . $fullOnSmsDetails['username'] . '&pwd=' . $fullOnSmsDetails['password'] . '&phone=' . $mobile . '&msg=' . urlencode($message);
        // echo $finalUrl;                    
        // Generate curl request
        $session = curl_init($finalUrl);
        // Tell curl to use HTTP POST
        curl_setopt($session, CURLOPT_POST, false);
        curl_setopt($session, CURLOPT_HEADER, false);
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
        // obtain response
        $response = curl_exec($session);
        $founded = false;
        if (substr($response, 0, 4) == 'true') {
            $founded = true;
        }
        curl_close($session);
        return $founded;
    }

    public function sendWebMail($data) {
        $url = 'http://sendgrid.com/';
        $OptionsDB = new Admin_Model_Options();
        $sendgridDetails = $OptionsDB->getSendgridDetails();
        $username = $sendgridDetails['username'];
        $password = $sendgridDetails['password'];
        $fromEmail = $OptionsDB->getAdminEmail();
        $toEmail = $data['toEmail'];
        $subject = $data['subject'];
        $body = $data['body'];
        $json_string = array(
            'to' => array(
                $toEmail
            ),
            'unique_args' => $data['uniqueArgs']
        );

        $params = array(
            'api_user' => $username,
            'api_key' => $password,
            'x-smtpapi' => json_encode($json_string),
            'to' => $toEmail,
            'subject' => $subject,
            'html' => $body,
            'from' => $fromEmail,
        );


        $request = $url . 'api/mail.send.json';

        // Generate curl request
        $session = curl_init($request);
        // Tell curl to use HTTP POST
        curl_setopt($session, CURLOPT_POST, true);
        // Tell curl that this is the body of the POST
        curl_setopt($session, CURLOPT_POSTFIELDS, $params);
        // Tell curl not to return headers, but do return the response
        curl_setopt($session, CURLOPT_HEADER, false);
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

        // obtain response
        $response = curl_exec($session);
        curl_close($session);

        // print everything out
        print_r($response);
    }

    public function sendMail($data) {
        $OptionsDB = new Admin_Model_Options();
        Zend_Loader::loadClass('System_Header');
        $fromEmail = $OptionsDB->getAdminEmail();
        $fromName = 'Savan Koradia @VijaySales';
        $toEmail = $data['toEmail'];
        //$receivers = array($toEmail);
        $toName = ($data['toName'] == null) ? $toEmail : $data['toName'];
        $subject = $data['subject'];
        $body = $data['body'];
        $header = new System_Header();
        $header->addFilterSetting('subscriptiontrack', 'enable', 0);
        $header->setUniqueArgs($data['uniqueArgs']);
        //$header->addTo($receivers);
        //$header->as_string();
        $mail = new Zend_Mail();
        $mail->setFrom($fromEmail, $fromName);
        $mail->addTo($toEmail, $toName);
        $mail->setSubject($subject);
        $mail->setBodyHtml($body);
        $sendgridDetails = $OptionsDB->getSendgridDetails();
        $mailServerPath = $sendgridDetails['serverPath'];
        $username = $sendgridDetails['username'];
        $password = $sendgridDetails['password'];
        $config = array('ssl' => 'tls',
            'port' => '465',
            'auth' => 'login',
            'username' => $username,
            'password' => $password);
        $transport = new Zend_Mail_Transport_Smtp($mailServerPath, $config);
        //    $mail->addHeader('X-SMTPAPI', $header->asJSON());
        $mail->send($transport);
    }

    public function sendmsgsuccessAction() {
        $this->_helper->layout()->disableLayout();
        $status = $this->getRequest()->getParam("status");
        $this->view->status = $status;
    }

    /**
     * never touch this method...
     *
     */
    public function eventtrackAction() {
        $values = $_POST;
        $insertId = $values['insertId'];
        $from = $values['from'];
        if (isset($from) && $from == "localhost" && $insertId != null && isset($insertId)) {
            $db = new Admin_Model_Sentnotifications();
            $byInsertId = $db->getByInsertId($insertId);
            $emailEvents = $byInsertId['email']->events;
            $timestamp = $values['timestamp'];
            switch ($values['event']) {
                case 'open':
                    $emailEvents->open = $timestamp;
                    break;
                case 'click':
                    $emailEvents->click = $timestamp;
                    break;
                case 'dropped':
                    $emailEvents->dropped = $timestamp;
                    break;
                case 'delivered':
                    $emailEvents->delivered = $timestamp;
                    break;
                case 'bounce':
                    $emailEvents->bounce = $timestamp;
                    break;
                case 'spamreport':
                    $emailEvents->spamreport = $timestamp;
                    break;
                case 'unsubscribe':
                    $emailEvents->unsubscribe = $timestamp;
                    break;
            }

            $localEmail = array(
                'email' => $byInsertId['email']->email,
                'events' => $emailEvents,
            );

            #update data
            $db->update(array('email' => json_encode($localEmail)), $insertId);
        }
    }

    public function aboutusAction() {
        $db = new Admin_Model_Tc();
        $tc = $db->getAboutUs();
        $this->view->tc = $tc;
    }

}

